package cn.vihub.controller;

import cn.vihub.utils.Result;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.PutObjectBaseArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.UUID;

/**
 * @Author: 秋晚
 * @Date: 2025/7/25 09:55
 * @Description:
 **/
//因为图片上传不需要走网关 所以在控制层解决跨域问题
@CrossOrigin
@RestController
@RefreshScope
@RequestMapping("shop-file/img")
public class ImgController {

    @Value("${minio.imgurl}")
    private String imgurl;
    @Autowired
    private MinioClient minioClient;

    @PostMapping
    public Result<Object> upload(MultipartFile file) throws Exception {
        //创建实例化对象
        MinioClient build = MinioClient.builder().endpoint("http:127.0.0.1:9000").build();
        //获取原来文件的后缀名
        String[] split = file.getOriginalFilename().split("\\.");
        String extName = split[split.length - 1];
        //生成随机文件名
        String fileName = UUID.randomUUID().toString()+extName;
        //构建
        minioClient.putObject(PutObjectArgs.builder()
                .bucket("2301a")
                .object(fileName)
                .stream(file.getInputStream(),file.getSize(),-1)
                .build());

        String fileUrl=imgurl+fileName;
        HashMap<String, String> map = new HashMap<>();
        map.put("fileName",fileName);
        map.put("fileUrl",fileUrl);
        //生成上传成功页面回显的文件路径
        return Result.success(map);

    }






}
